package com.smap.vector;

import com.smap.core.Bbox;
import com.smap.core.XY;

/**
 * for geometry calculation
 *
 * @author shen
 *
 */
public class LineSegment {
	public XY p1;
	public XY p2;
	private Double slope;
	Bbox envelope = new Bbox();

	LineSegment(XY p1, XY p2) {
		this.p1 = p1;
		this.p2 = p2;
		envelope.expand(p1).expand(p2);
		// calculate slope;
		if (p2.x != p1.x) {
			// otherwise it is a vertical line
			slope = (p2.y - p1.y) / (p2.x - p1.x);
		}
	}

	public boolean contains(XY p3) {
		if (!envelope.contains(p3)) {
			return false;
		}
		if (slope != null) {
			double theY = p1.y + (p3.x - p1.x) * slope;
			XY newP = new XY(p3.x, theY);
			if (!p3.equals(newP)) {
				return false;
			}
		}
		return true;
	}

	public Bbox getEnvelope() {
		return envelope;
	}

	@Override
	public String toString() {
		return "LineSegment [p1=" + p1 + ", p2=" + p2 + "]";
	}

}
